﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SugarWebApi.Processors
{

	public class SoapV2Translator
	{

		#region ToSugarEntries

		public static SugarEntry[] ToSugarEntries(
			SugarSoapV2.entry_value[] entriesbysoap,
			SugarIndexResolver indexresolver)
		{
			List<SugarEntry> entries = new List<SugarEntry>();
			foreach (SugarSoapV2.entry_value entry in entriesbysoap)
			{
				entries.Add(ToSugarEntry(entry, indexresolver));
			}
			return entries.ToArray();
		}

		public static SugarEntry ToSugarEntry(
			SugarSoapV2.entry_value entrybysoap,
			SugarIndexResolver indexresolver)
		{
			SugarEntry entry = new SugarEntry(
				indexresolver,
				ToObjects(entrybysoap.name_value_list, indexresolver));

			return entry;
		}

		public static object[] ToObjects(
			SugarSoapV2.name_value[] values,
			SugarIndexResolver indexresolver)
		{
			List<object> objects = new List<object>();
			foreach (SugarSoapV2.name_value value in values)
			{
				objects.Add(indexresolver.IndexOf(value.name));
			}
			return objects.ToArray();
		}

		#endregion

		#region SugarModule

		public static SugarModule[] ToSugarModules(
			SugarWebConext context,
			string[] modulesbysoap)
		{
			List<SugarModule> modules = new List<SugarModule>();
			foreach (string modulebysoap in modulesbysoap)
			{
				modules.Add(ToSugarModule(context, modulebysoap));
			}
			return modules.ToArray();
		}

		public static SugarModule ToSugarModule(
			SugarWebConext context,
			string  modulebysoap)
		{
			SugarModule module = new SugarModule(context);
			module.ModuleName = modulebysoap;
			return module;
		}

		#endregion

		public static SugarField[] ToSugarFields(
			SugarWebConext context,
			SugarSoapV2.field[] fieldsbysoap)
		{
			List<SugarField> fields = new List<SugarField>();
			foreach (SugarSoapV2.field field in fieldsbysoap)
			{
				fields.Add(ToSugarField(context, field));
			}
			return fields.ToArray();
		}

		public static SugarField ToSugarField(
			SugarWebConext context,
			SugarSoapV2.field fieldbysoap)
		{
			SugarField field = new SugarField(context);
			field.DefaultValue = fieldbysoap.default_value;
			field.Label = fieldbysoap.label;
			field.Name = fieldbysoap.name;
			// field = fieldbysoap.options;
			field.Required = (fieldbysoap.required != 0);
			field.Type = fieldbysoap.type;
			return field;
		}


	}
}
